<?php

/*
    API REST controller answers to AJAX calls.
    Used for auto-complete function.
 */

class Controller_Api extends Controller_Rest {
    protected $default_format = 'json';
    protected $format = 'json';
    
    //Returns movie titles based on the provided search phrase.
    public function get_titles() {
        $this->default_format = 'application/json';
        
        $term = '%' . Input::get('term') . '%';

        $matching_titles =  Model_Orm_Movie::query()
            ->select('id', 'title_lv', 'title_en', 'duration', 'year')
            ->where('title_lv', 'LIKE', $term)
            ->or_where('title_en', 'LIKE', $term)
            ->get();

        $results = array();

        foreach($matching_titles as $title) {        
            if(mb_stripos($title->title_lv, Input::get('term')) !== false) {
                array_push($results, array('value' => $title->id, 'label' => $title->title_lv . ' (' . $title->year . ')', 'duration'=>$title->duration));    
            } else {
                array_push($results, array('value' => $title->id, 'label' => $title->title_en . ' (' . $title->year . ')', 'duration'=>$title->duration));
            }
        }

        //Returning HTTP status code 200 (OK) to confirm successful call.
        return $this->response(Format::forge($results)->to_json(), 200);
    }
    
    public function get_seatinfo() {
        $id = Input::get('show_id');
        
        if(is_null($id)) {
            return $this->response(Format::forge(array())->to_json(), 404);
        }
        
        $show_orders = Model_Orm_Order::query()->select('*')->where('show_id', $id);
        
        if(is_null($show_orders)) {
            return $this->response(Format::forge(array())->to_json(), 200);
        }

        $reservations = $show_orders->get('reservations');
        return $this->response(Format::forge($reservations)->to_json(), 200);
    }
}
